package com.hanson.service;

import com.hanson.entity.MenuBean;
import com.hanson.mapper.MenuBeanMapper;
import com.hanson.mapper.UserMenuBeanMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.*;

@Service
public class MenuService {
	@Autowired
	private MenuBeanMapper menuBeanMapper;
	@Autowired
	private UserMenuBeanMapper userMenuBeanMapper;
	
	public List<MenuBean> getMenus(List<Integer> userTypes) {
		List<String> menuIdsList = userMenuBeanMapper.selectMenusIdByUserType(userTypes);
		List<MenuBean> returnList = new ArrayList<>();
		if(!CollectionUtils.isEmpty(menuIdsList)){
			List<MenuBean>  menuBeanList = menuBeanMapper.selectByPrimaryKeys(menuIdsList);
			if(!CollectionUtils.isEmpty(menuBeanList)){
				Map<String,MenuBean> menuMap = new HashMap<>();
				for(int i = 0; i < menuBeanList.size(); i++){
					if(menuBeanList.get(i).getPid().equals("-1")){
						continue;
					}
					MenuBean menuBean = menuBeanMapper.selectByPrimaryKey(menuBeanList.get(i).getPid());
					if(menuMap.containsKey(menuBean.getId())){
						menuMap.get(menuBean.getId()).getChildren().add(menuBeanList.get(i));
					}else{
						menuBean.getChildren().add(menuBeanList.get(i));
						menuMap.put(menuBean.getId(), menuBean);
					}
				}
				
				for(Map.Entry<String, MenuBean> entry : menuMap.entrySet()){
					Collections.sort(entry.getValue().getChildren(),new Comparator<MenuBean>() {
		                @Override
		                public int compare(MenuBean o1, MenuBean o2) {
		                    return o2.getSort() - o1.getSort();
		                }
		            });
					returnList.add(entry.getValue());
				}
				
				Collections.sort(returnList,new Comparator<MenuBean>() {
	                @Override
	                public int compare(MenuBean o1, MenuBean o2) {
	                    return o2.getSort() - o1.getSort();
	                }
	            });
			}
		}
		return returnList;
	}
}
